package org.bugjail.integration.mantis.dataaccess.objects;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.bugjail.integration.mantis.data.CR;
import org.bugjail.integration.mantis.dataaccess.database.QueryException;
import org.bugjail.integration.mantis.dataaccess.database.QueryManager;

public class RepositoryCR {

	private final String PROPERTIES_FILE = "/org/bugjail/integration/mantis/dataaccess/properties/cr.properties";
	private final String PROPERTY_GET_CR = "get.cr";

	public CR getCRById(int id) {
		CR cr = null;
		QueryManager queryManager = null;
		try {
			try {
				queryManager = new QueryManager(PROPERTIES_FILE);
				PreparedStatement statement = queryManager
						.getPreparedStatement(PROPERTY_GET_CR);
				statement.setInt(1, id);
				ResultSet rs = statement.executeQuery();
				if (rs.next()) {
					cr = extractCRFromResultSet(rs, queryManager);
				}
			} finally {
				QueryManager.close(queryManager);
			}
		} catch (Exception e) {
			throw new QueryException(e.getMessage());
		}
		return cr;
	}

	private CR extractCRFromResultSet(ResultSet rs, QueryManager queryManager) throws SQLException {
		CR cr = new CR();
		cr.setId(rs.getInt("id"));
		cr.setStatus(rs.getInt("statuscode"));
		cr.setReporter(rs.getString("reporter"));
		cr.setHandler(rs.getString("handler"));
		cr.setSummary(rs.getString("summary"));
		return cr;
	}
	
	public static void main(String[] args) {
		RepositoryCR rcr = new RepositoryCR();
		CR cr = rcr.getCRById(36238);
		System.out.println(cr.getHandler());
		System.out.println(cr.getReporter());
		System.out.println(cr.getStatus());
		System.out.println(cr.getSummary());
		System.out.println(cr.getId());
	}
}
